<?php

namespace app\common\model;

use think\Model;
use app\bsadmin\model\Admin as AdminModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Resume as ResumeModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\UserQq as UserQqModel;
use app\common\model\UserWx as UserWxModel;
use app\common\model\UserApple as UserAppleModel;
use app\common\model\ScoreTask as ScoreTaskModel;
use app\common\model\UserNotice as UserNoticeModel;
use app\common\model\Vip as VipModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\UserAvatarExamine as UserAvatarExamineModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\event\ScoreTask as ScoreTaskEvent;

class User extends Model
{
    public static function getUserInfoAll($id)
    {
        $Field = [
            'user.id,user.user,user.mobile,user.email,user.status,user.disable_msg,user.create_time,user.update_time',
            'user_info.pid,user_info.nickname,user_info.headimg,user_info.name,user_info.idcard,user_info.role_type,user_info.score,user_info.create_time as info_create_time,user_info.update_time as info_update_time',
            'puser.nickname as pnickname,puser.headimg as pheadimg',
            'user_timer.online_time,user_timer.online_ip,user_timer.online_devices,user_timer.login_time,user_timer.login_ip,user_timer.login_devices,user_timer.register_time,user_timer.register_ip,user_timer.register_devices',
        ];
        $Find = self::alias('user')->where(['user.id' => $id])
            ->join('user_info user_info', 'user_info.uid = user.id', 'LEFT')
            ->join('user_info puser', 'puser.uid = user_info.pid', 'LEFT')
            ->join('user_timer user_timer', 'user_timer.uid = user.id', 'LEFT')
            ->field(implode(',', $Field))
            ->withAttr('nickname', function ($v, $d) {
                return $v ? base64_decode($v) : '';
            })
            ->withAttr('pnickname', function ($v, $d) {
                return $v ? base64_decode($v) : '';
            })
            ->withAttr('pheadimg', function ($v, $d) {
                return $v ? config('web.imgurl') . $v : '';
            })
            ->withAttr('info_create_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('info_update_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('online_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('login_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('register_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('download_resume', function ($v, $d) {
                $ruleAdded = UserVipRuleModel::alias('rule')
                    ->join('vip_value_added va', 'va.id=rule.rid')
                    ->where(['rule.uid' => $d['id'], 'rule.status' => 1, 'rule.is_company' => 1, 'va.type' => 2/* 2表示简历下载 */, 'rule.vid' => null])
                    ->whereTime('rule.expiry_time', '>', time())
                    ->sum('rule.surplus_value');
                return $v + $ruleAdded;
            })
            ->find();
        if ($Find) {
            $Find->bind_qq = UserQqModel::where(['uid' => $Find->id])->field('id,nickname,headimgurl')->withAttr('nickname', function ($v) {
                return $v ? base64_decode($v) : '';
            })->find();
            $Find->bind_wx = UserWxModel::where(['uid' => $Find->id])->field('id,nickname,wx_openid,headimgurl')->withAttr('nickname', function ($v) {
                return $v ? base64_decode($v) : '';
            })->withAttr('wx_openid', function ($v) {
                return $v ? 1 : 0;
            })->find();
            $Find->bind_apple = UserAppleModel::where(['uid' => $Find->id])->field('id')->find();
            $Find->after_avatar = UserAvatarExamineModel::where(['uid' => $Find->id, 'status' => 0])->withAttr('after_avatar', function ($v, $data) {
                return config('web.imgurl') . $v;
            })->find();
        }
        return $Find;
    }
    /**
     * [getPassword 密码加密]
     * @param  string $hash     [description]
     * @param  string $password [description]
     * @return [type]           [description]
     */
    public static function getPassword($hash = '', $password = '')
    {
        return md5(sha1(md5(strtoupper($hash) . '&' . $password . '&' . $hash)));
    }
    /**
     * getUserPassword 获取密码
     */
    public static function getUserPassword($where)
    {
        return self::where($where)->field('id,password,password_hash')->find();
    }
    public static function getWebUserInfo($where)
    {
        $Field = [
            'user.id,user.user,user.mobile,user.email,user.status,user.disable_msg,user.create_time,user.update_time',
            'user_info.pid,user_info.nickname,user_info.headimg,user_info.role_type,user_info.score',
            'puser.nickname as pnickname,puser.headimg as pheadimg',
            'vip.company_vip_level,vip.company_vip_time,vip.personal_vip_level,vip.personal_vip_time,vip.release_jobs_sum,vip.download_resume,vip.im_max_people,vip.top_day,vip.refresh_sum,vip.urgent_day,vip.invite_aninterview,vip.job_fair,vip.today_down_resume,vip.show_delivery_resume,vip.im_max_people_today',
            'user_timer.online_time,user_timer.online_ip,user_timer.online_devices,user_timer.login_time,user_timer.login_ip,user_timer.login_devices,user_timer.register_time,user_timer.register_ip,user_timer.register_devices'
        ];
        $Find = self::alias('user')->where($where)
            ->join('user_info user_info', 'user_info.uid = user.id', 'LEFT')
            ->join('user_info puser', 'puser.uid = user_info.pid', 'LEFT')
            ->join('user_vip vip', 'vip.uid = user.id', 'LEFT')
            ->join('user_timer user_timer', 'user_timer.uid = user.id', 'LEFT')
            ->field(implode(',', $Field))
            ->withAttr('user', function ($v, $d) {
                return $v ? $v : '';
            })
            ->withAttr('nickname', function ($v, $d) {
                return $v ? base64_decode($v) : '';
            })
            ->withAttr('headimg', function ($v, $d) {
                return $v ? config('web.imgurl') . $v : '';
            })
            ->withAttr('mobile', function ($v, $d) {
                return $v ? substr_replace($v, '****', 3, 4) : '';
            })
            ->withAttr('email', function ($v, $d) {
                if ($v) {
                    //隐藏邮箱部分内容
                    $email = explode('@', $v);
                    if (empty($email[0]) || empty($email[1])) {
                        return '';
                    } else {
                        return substr_replace($email[0], '****', 3, mb_strlen($email[0])) . '@' . $email[1];
                    }
                } else {
                    return '';
                }
            })
            ->withAttr('pnickname', function ($v, $d) {
                return $v ? base64_decode($v) : '';
            })
            ->withAttr('pheadimg', function ($v, $d) {
                return $v ? config('web.imgurl') . $v : '';
            })
            ->withAttr('online_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('login_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('register_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('company_vip_time', function ($v, $d) {
                if ($v) {
                    return $v > time() ? date('Y-m-d', $v) : '已过期';
                } else {
                    return '';
                }
            })
            ->withAttr('personal_vip_time', function ($v, $d) {
                if ($v) {
                    return $v > time() ? date('Y-m-d', $v) : '已过期';
                } else {
                    return '';
                }
            })
            ->withAttr('company_vip_level', function ($v, $d) {
                return $v ? $v : 0;
            })
            ->withAttr('personal_vip_level', function ($v, $d) {
                return $v ? $v : 0;
            })
            ->withAttr('download_resume', function ($v, $d) {
                $ruleAdded = UserVipRuleModel::alias('rule')
                    ->join('vip_value_added va', 'va.id=rule.rid')
                    ->where(['rule.uid' => $d['id'], 'rule.status' => 1, 'rule.is_company' => 1, 'va.type' => 2/* 2表示简历下载 */, 'rule.vid' => null])
                    ->whereTime('rule.expiry_time', '>', time())
                    ->sum('rule.surplus_value');
                return $v + $ruleAdded;
            })
            ->find();
        if ($Find) {
            $adviserDefault = AdminModel::where(['adviser_default' => 1])->field('nickname,headimg,mobile,email,other_contact,other_img')->withAttr('headimg', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->withAttr('other_img', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->find();
            $Find->company_id = 0;
            $Find->resume_id = 0;
            $CompanyModel = CompanyModel::alias('c')->where(['c.uid' => $Find->id])->join('admin adviser', 'adviser.id=c.adviser_id', 'LEFT')->field('c.id,c.title,adviser.nickname,adviser.headimg,adviser.mobile,adviser.email,adviser.other_contact,adviser.other_img')->withAttr('headimg', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->withAttr('other_img', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->find();
            if ($CompanyModel) {
                $Find->company_id = $CompanyModel->id;
                $Find->company_name = $CompanyModel->title;
                if ($CompanyModel->nickname)
                    $Find->adviser = $CompanyModel;
            }
            $ResumeModel = ResumeModel::alias('r')->where(['r.uid' => $Find->id])->join('admin adviser', 'adviser.id=r.adviser_id', 'LEFT')->field('r.id,r.name,adviser.nickname,adviser.headimg,adviser.mobile,adviser.email,adviser.other_contact,adviser.other_img')->withAttr('headimg', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->withAttr('other_img', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->find();
            if ($ResumeModel) {
                $Find->resume_id = $ResumeModel->id;
                $Find->resume_name = $ResumeModel['name'];
                if ($ResumeModel->nickname)
                    $Find->adviser = $ResumeModel;
            }
            if (!$Find->adviser)
                $Find->adviser = $adviserDefault;
            $Find->bind_qq = UserQqModel::where(['uid' => $Find->id])->field('id,nickname,headimgurl')->withAttr('nickname', function ($v) {
                return $v ? base64_decode($v) : '';
            })->find();
            $Find->bind_wx = UserWxModel::where(['uid' => $Find->id])->field('id,nickname,wx_openid,headimgurl')->withAttr('nickname', function ($v) {
                return $v ? base64_decode($v) : '';
            })->withAttr('wx_openid', function ($v) {
                return $v ? 1 : 0;
            })->find();
            $Task = ScoreTaskModel::where(['event' => 'sign_in'])->field('id,title,tips,event,score,url,repeat,repeat_sum')->find()->toArray();
            if ($Task) {
                if (ScoreTaskEvent::isComplete($Find->id, $Task) == ScoreTaskEvent::COMPLETE_STATUS_0) {
                    $Find->sign_in_status = 0;
                } else {
                    $Find->sign_in_status = 1;
                }
            }
            $Find->company_vip = VipModel::where(['level' => $Find->company_vip_level, 'is_company' => 1, 'status' => 1])->field('title,icon')->find();
            $Find->personal_vip = VipModel::where(['level' => $Find->personal_vip_level, 'is_company' => 0, 'status' => 1])->field('title,icon')->find();
            $Find->jobs_sum = JobsModel::where(['company_id' => $Find->company_id])->count();
            $Find->notice = self::initNotice($Find->id);
            if (!empty(request()->AppInfo['app_key'])) {
                $TokenData = [
                    'uid' => $Find->id,
                    'resume_id' => $Find->resume_id,
                    'company_id' => $Find->company_id,
                    'expire_time' => time() + 3600 * 24 * 7
                ];
                $Find->api_token = self::encrypt(base64_encode(json_encode($TokenData, JSON_UNESCAPED_UNICODE)), request()->AppInfo['app_key']);
            }
            $Find->after_avatar = UserAvatarExamineModel::where(['uid' => $Find->id, 'status' => 0])->withAttr('after_avatar', function ($v, $data) {
                return config('web.imgurl') . $v;
            })->find();
        }
        return $Find;
    }
    public static function getAppUserInfo($where)
    {
        $Field = [
            'user.id,user.user,user.mobile,user.email,user.status,user.disable_msg,user.create_time,user.update_time',
            'user_info.pid,user_info.nickname,user_info.headimg,user_info.role_type,user_info.score',
            'puser.nickname as pnickname,puser.headimg as pheadimg',
            'vip.company_vip_level,vip.company_vip_time,vip.personal_vip_level,vip.personal_vip_time,vip.release_jobs_sum,vip.download_resume,vip.im_max_people,vip.top_day,vip.refresh_sum,vip.urgent_day,vip.invite_aninterview,vip.job_fair,vip.today_down_resume,vip.show_delivery_resume,vip.im_max_people_today',
            'user_timer.online_time,user_timer.online_ip,user_timer.online_devices,user_timer.login_time,user_timer.login_ip,user_timer.login_devices,user_timer.register_time,user_timer.register_ip,user_timer.register_devices'
        ];
        $Find = self::alias('user')->where($where)
            ->join('user_info user_info', 'user_info.uid = user.id', 'LEFT')
            ->join('user_info puser', 'puser.uid = user_info.pid', 'LEFT')
            ->join('user_vip vip', 'vip.uid = user.id', 'LEFT')
            ->join('user_timer user_timer', 'user_timer.uid = user.id', 'LEFT')
            ->field(implode(',', $Field))
            ->withAttr('user', function ($v, $d) {
                return $v ? $v : '';
            })
            ->withAttr('nickname', function ($v, $d) {
                return $v ? base64_decode($v) : '';
            })
            ->withAttr('headimg', function ($v, $d) {
                return $v ? config('web.imgurl') . $v : '';
            })
            ->withAttr('mobile', function ($v, $d) {
                return $v ? substr_replace($v, '****', 3, 4) : '';
            })
            ->withAttr('email', function ($v, $d) {
                if ($v) {
                    //隐藏邮箱部分内容
                    $email = explode('@', $v);
                    if (empty($email[0]) || empty($email[1])) {
                        return '';
                    } else {
                        return substr_replace($email[0], '****', 3, mb_strlen($email[0])) . '@' . $email[1];
                    }
                } else {
                    return '';
                }
            })
            ->withAttr('pnickname', function ($v, $d) {
                return $v ? base64_decode($v) : '';
            })
            ->withAttr('pheadimg', function ($v, $d) {
                return $v ? config('web.imgurl') . $v : '';
            })
            ->withAttr('online_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('login_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('register_time', function ($v, $d) {
                return $v ? date('Y-m-d H:i:s', $v) : '';
            })
            ->withAttr('company_vip_time', function ($v, $d) {
                if ($v) {
                    return $v > time() ? date('Y-m-d', $v) : '已过期';
                } else {
                    return '';
                }
            })
            ->withAttr('personal_vip_time', function ($v, $d) {
                if ($v) {
                    return $v > time() ? date('Y-m-d', $v) : '已过期';
                } else {
                    return '';
                }
            })
            ->withAttr('company_vip_level', function ($v, $d) {
                return $v ? $v : 0;
            })
            ->withAttr('personal_vip_level', function ($v, $d) {
                return $v ? $v : 0;
            })->find();
        if ($Find) {
            $adviserDefault = AdminModel::where(['adviser_default' => 1])->field('nickname,headimg,mobile,email,other_contact,other_img')->withAttr('headimg', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->withAttr('other_img', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->find();
            $Find->company_id = 0;
            $Find->resume_id = 0;
            $CompanyModel = CompanyModel::alias('c')->where(['c.uid' => $Find->id])->join('admin adviser', 'adviser.id=c.adviser_id', 'LEFT')->field('c.id,adviser.nickname,adviser.headimg,adviser.mobile,adviser.email,adviser.other_contact,adviser.other_img')->withAttr('headimg', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->withAttr('other_img', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->find();
            if ($CompanyModel) {
                $Find->company_id = $CompanyModel->id;
                $Find->company_name = $CompanyModel->title;
                if ($CompanyModel->nickname)
                    $Find->adviser = $CompanyModel;
            }
            $ResumeModel = ResumeModel::alias('r')->where(['r.uid' => $Find->id])->join('admin adviser', 'adviser.id=r.adviser_id', 'LEFT')->field('r.id,adviser.nickname,adviser.headimg,adviser.mobile,adviser.email,adviser.other_contact,adviser.other_img')->withAttr('headimg', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->withAttr('other_img', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : $v;
            })->find();
            if ($ResumeModel) {
                $Find->resume_id = $ResumeModel->id;
                $Find->resume_name = $ResumeModel['name'];
                if ($ResumeModel->nickname)
                    $Find->adviser = $ResumeModel;
            }
            if (!$Find->adviser)
                $Find->adviser = $adviserDefault;
            $Find->bind_qq = UserQqModel::where(['uid' => $Find->id])->field('id,nickname,headimgurl')->withAttr('nickname', function ($v) {
                return $v ? base64_decode($v) : '';
            })->find();
            $Find->bind_wx = UserWxModel::where(['uid' => $Find->id])->field('id,nickname,wx_openid,headimgurl')->withAttr('nickname', function ($v) {
                return $v ? base64_decode($v) : '';
            })->withAttr('wx_openid', function ($v) {
                return $v ? 1 : 0;
            })->find();
            $Find->bind_apple = UserAppleModel::where(['uid' => $Find->id])->field('id')->find();
            $Task = ScoreTaskModel::where(['event' => 'sign_in'])->field('id,title,tips,event,score,url,repeat,repeat_sum')->find()->toArray();
            if ($Task) {
                if (ScoreTaskEvent::isComplete($Find->id, $Task) == ScoreTaskEvent::COMPLETE_STATUS_0) {
                    $Find->sign_in_status = 0;
                } else {
                    $Find->sign_in_status = 1;
                }
            }
            $Find->company_vip = VipModel::where(['level' => $Find->company_vip_level, 'is_company' => 1, 'status' => 1])->field('title,icon')->find();
            $Find->personal_vip = VipModel::where(['level' => $Find->personal_vip_level, 'is_company' => 0, 'status' => 1])->field('title,icon')->find();
            $Find->jobs_sum = JobsModel::where(['company_id' => $Find->company_id])->count();
            $Find->notice = self::initNotice($Find->id);
            if (!empty(request()->AppInfo['app_key'])) {
                $TokenData = [
                    'uid' => $Find->id,
                    'resume_id' => $Find->resume_id,
                    'company_id' => $Find->company_id,
                    'expire_time' => time() + 3600 * 24 * 7
                ];
                $Find->api_token = self::encrypt(base64_encode(json_encode($TokenData, JSON_UNESCAPED_UNICODE)), request()->AppInfo['app_key']);
            }
            $Find->after_avatar = UserAvatarExamineModel::where(['uid' => $Find->id, 'status' => 0])->withAttr('after_avatar', function ($v, $data) {
                return config('web.imgurl') . $v;
            })->find();
        }
        return $Find;
    }
    public static function initNotice($uid)
    {
        $UserNoticeModel = UserNoticeModel::where(['uid' => $uid])->withoutField('id,uid,update_time,create_time')->find();
        if ($UserNoticeModel) {
            return $UserNoticeModel;
        } else {
            $UserNoticeModel = new UserNoticeModel;
            $UserNoticeModel->uid = $uid;
            if ($UserNoticeModel->save()) {
                return self::initNotice($uid);
            } else {
                return null;
            }
        }
    }
    public static function decrypt($data, $rsa_privatekey)
    {
        $split = str_split($data, 172);  // 1024 bit  固定172
        $crypto = '';
        foreach ($split as $chunk) {
            $isOkay = openssl_private_decrypt(base64_decode($chunk), $decryptData, $rsa_privatekey);  // base64在这里使用，因为172字节是一组，是encode来的
            if (!$isOkay) {
                return false;
            }
            $crypto .= $decryptData;
        }
        return $crypto;
    }
    public static function encrypt($data, $rsa_publickey)
    {
        $split = str_split($data, 117);  // 1024 bit && OPENSSL_PKCS1_PADDING  不大于117即可
        $crypto = '';
        foreach ($split as $chunk) {
            $isOkay = openssl_public_encrypt($chunk, $encryptData, $rsa_publickey);
            if (!$isOkay) {
                return false;
            }
            $crypto .= base64_encode($encryptData);
        }
        return $crypto;
    }
}
